<template>
  <el-autocomplete
    class="xxx"
    v-model="city"
    :fetch-suggestions="querySearchAsync"
    placeholder="城市名称"
    @select="handleSelect"
    value-key="snm"
  >
    <template #append>
      <el-icon class="el-input__icon" @click="handleIconClick">
        <Search />
      </el-icon>
    </template>
    <template #default="{ item }">
      <div class="auto_itme">
        <div class="value">{{ item.snm }}</div>
        <span class="link">{{ item.snmpy }}</span>
      </div>
    </template>
  </el-autocomplete>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import $axios from '../../tools/axios'
import { Search } from '@element-plus/icons-vue'

import { useStationStore } from '../../stores/station'
import { storeToRefs } from 'pinia'

const stationStore = useStationStore()

const { city } = storeToRefs(stationStore)

const links = ref([])

const handleIconClick = () => {
  stationStore.loadByCity()
}

const loadAll = () => {
  return [
    { value: 'vue', link: 'https://github.com/vuejs/vue' },
    { value: 'element', link: 'https://github.com/ElemeFE/element' },
    { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
    { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
    { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
    { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
    { value: 'babel', link: 'https://github.com/babel/babel' }
  ]
}

const querySearchAsync = async (queryString, cb) => {
  const results = queryString ? queryString : 'all'

  const path = '/st/q/4auto/' + results
  $axios
    .get(path)
    .then((response) => {
      const { data: res } = response
      if (res.code === 200) {
        cb(res.data)
      } else {
        cb([])
      }
    })
    .catch((err) => {
      console.log(err)
      cb([])
    })
  // const { data: res } = await $axios.get(path)
  // if (res.code === 200) {
  //   cb(res.data)
  // } else {
  //   cb([])
  // }
}

const handleSelect = (item) => {
  console.log(item)
}

onMounted(() => {
  links.value = loadAll()
})
</script>
<style lang="scss" scoped>
.auto_itme {
  display: flex;
  justify-content: space-between;
}
</style>
